from odoo import fields, models, api
import re


class ProductTemplate(models.Model):
    _inherit = "product.template"

    customer_item_code_ids = fields.One2many('customer.item.code', 'product_id', 'Customer Item Code')
    application_product_id = fields.Many2one('application.product', string="PCB Application")
    jmi_author = fields.Char(string="JMI Author")
    serial_number = fields.Char(string="Serial Number", copy=False)  # 流水号

    is_engineering_admin = fields.Boolean(string="Is Engineering 工程审批管理员",
                                          compute="_compute_is_engineering_admin", )

    def update_versions_from_name(self):
        # 获取所有成品记录
        products = self.env['product.template'].search([('categ_id', '=', 6)])
        for product in products:
            # 检查 versions 字段是否为空
            if not product.versions:
                # 从 name 中提取版本信息
                name = product.name
                # 使用正则表达式匹配最后的字母加数字的模式
                import re
                match = re.search(r'([A-Za-z]+)\d+$', name)
                if match:
                    # 提取版本信息
                    version = match.group(0)
                    # 赋值给 versions 字段
                    product.versions = version

    @api.model_create_multi
    def create(self, vals_list):
        res = super().create(vals_list)
        for rec in res:
            # 正则提取流水号
            rec.upload_serial_number()
        return res

    def write(self, vals):
        res = super().write(vals)
        if isinstance(vals, list):
            for record in vals:
                if 'name' in record:
                    self.upload_serial_number()
        else:
            if 'name' in vals:
                self.upload_serial_number()
        return res

    def upload_serial_number(self):
        for rec in self:
            finished = self.env.ref('sb_sale.finished_product_type').id
            semi = self.env.ref('sb_sale.semi_product_type').id
            c = self.env['product.category'].sudo().search([('code', '=', 'OPFP')])
            c |= c.child_id
            category_ids = [finished, semi]
            category_ids.extend(c.ids)
            # 正则提取流水号
            if rec.categ_id.id in category_ids:
                if '-' in rec.name:
                    name = rec.name.split('-')[0]
                else:
                    name = rec.name
                # 如果存在S开头(新版本), 则使用S开头流水号, 否则使用数字流水号
                match = re.match(r'.*?(S\d+)', name)
                if match:
                    rec.write({'serial_number': match.group(1)})
                else:
                    match = re.match(r'[A-Z](?:\d*[A-Z])?(\d{6})[A-Z]', name)
                    if match:
                        rec.write({'serial_number': match.group(1)})


    @api.depends('name')
    def _compute_is_engineering_admin(self):
        for rec in self:
            rec.is_engineering_admin = self.env.user.has_group('sb_engineering.group_shy_engineering_manager')
